/**
 * Created by Administrator on 2017/3/21.
 */
import React, {Component} from 'react';
import {Form, Input, Radio, Select, Switch, Button, Tooltip, Icon, Col, Row, Checkbox} from 'antd';
import request from '@/utils/request';
import { connect } from 'dva';
import styles from '../../layouts/password.less';
import forEach from "lodash/forEach";
import groupBy from "lodash/groupBy";
const FormItem = Form.Item;
const { TextArea } = Input;
const CheckboxGroup = Checkbox.Group;
const RadioGroup = Radio.Group;
const Option = Select.Option;
class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.groupMap={
      meter_reading:"水表远传系统",
      revenue:"营收系统",
      user:"员工角色系统",
      pressure_monitoring:"智慧管网",
      wechat:"微信公众号",
      oa:"OA系统",
      erp:"ERP系统",
      inspect:"巡检系统",
      party_building:"党建系统",
      homepage:"首页",
      water_report:"水质报告",
      financial:"财务管理",
      safe_production:"安全生产",
      union:"公会系统",
      standing_books:"维修台账系统",
      digital_water_management:"数字供水管理",
      project:"工程项目管理",
      work_order:"派工系统",

    }
    this.state = {
      group:{},
      all_roles:[],
      companies:[],
      level:0,
      management_companies:sessionStorage.getItem('management_companies')?JSON.parse(sessionStorage.getItem('management_companies')):[],
      all_permission:(this.props.editRecord&&this.props.editRecord.configs)?this.props.editRecord.configs.all_permission:-1
    };
  }
  componentDidMount() {
    const that=this;
    this.changeRole()
    request(`/all_permissions`, {
      method: 'GET',
    }).then((response)=> {
      console.log('all_permissions', response)
      if(response.status===200){
        const group = groupBy(response.data.data, 'group')
        console.log('group', group);
        forEach(group, function (value, key) {
          that.setState({
            [key]: value.reduce((result, item)=> {
              item.label=item.display_name;
              item.value=item.id;
              result.push({label: item.display_name, value: item.id})
              return result
            }, [])
          })
          that.setState({
            [key + 'CheckedList']: [],
            [key + 'Indeterminate']: false,
            [key + 'CheckAll']: false,
          })

        });
        that.setState({
          group: group
        }, function () {
          if (this.props.editRecord){
            console.log('修改角色')
            const {permissions}=that.props.editRecord;
            const selectGroup = groupBy(permissions, 'group')
            forEach(selectGroup, function (value, key) {
              that.setState({
                [key + 'CheckedList']: value.reduce((result, item)=> {
                  result.push(item.id)
                  return result
                }, [])
              },function () {
                that.setState({
                  [key + 'Indeterminate']: !!that.state[key + 'CheckedList'].length && (that.state[key + 'CheckedList'].length < that.state[key].length),
                  [key + 'CheckAll']: that.state[key + 'CheckedList'].length === that.state[key].length,
                })
              })
            });

          }
        })
        console.log(this.state)
      }
    })
  }
  changeRole=(value,clear)=>{
    const that=this;
    request(`/all_roles`, {
      method: 'GET',
      params:{
        company_id:value
      }
    }).then((response)=> {
      console.log('all_permissions', response)
      if(response.status===200){
        if(clear){
          that.props.form.setFieldsValue({
            role_id:'',
          })
        }

        that.setState({
          all_roles:response.data.data
        })
      }
    })
  }
  changePassword=(e)=> {
    let value=e.target.value
    let level = 0;
    //正则表达式验证符合要求的
    if(/\d/.test(value)) level++; //数字
    if(/[A-Z]/.test(value)) level++; //小写
    if(/[a-z]/.test(value)) level++; //特殊字符
    if(value.length < 8||value.length > 16)  level=0;
    //逻辑处理
    this.setState({
      level:level
    })
  }
  renderXheckGroup = (group)=> {
    const that = this
    const formItemLayoutWithOutLabel = {
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 24},
      }
    }
    let result = []
    forEach(group, function (value, key) {

      result.push((
        <FormItem
          className={'custom-checkgroup'}
          key={key}
          {...formItemLayoutWithOutLabel}
        >
          <div className="checkgroup-title">
            <Checkbox
              indeterminate={that.state[key + 'Indeterminate']}
              onChange={(e)=>that.onCheckAllChange2(e,key)}
              checked={that.state[key + 'CheckAll']}
            >
              {that.groupMap[key]}
            </Checkbox>
          </div>
          <CheckboxGroup options={that.state[key]} value={that.state[key + 'CheckedList']} onChange={(node)=>that.onChange2(node,key)}/>
        </FormItem>
      ))
    });

    return result
  }
  onChange2 = (nodes,key) => {
    console.log(nodes)
    console.log(key)
    this.setState({
      [key + 'CheckedList']:nodes,
      [key + 'Indeterminate']: !!nodes.length && (nodes.length < this.state[key].length),
      [key + 'CheckAll']: nodes.length === this.state[key].length,
    })
  }
  onCheckAllChange2 = (e,key) => {
    this.setState({
      [key + 'CheckedList']: e.target.checked ? this.state[key].map((item, index)=> {
        return item.value
      }) : [],
      [key + 'Indeterminate']: false,
      [key + 'CheckAll']: e.target.checked,
    });
  }

  render() {
    const formItemLayoutWithLabel = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 7},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 15},
      }
    };

    const {getFieldDecorator} = this.props.form;
    let company_sign='请选择'
    if(this.props.editRecord&&this.props.editRecord.configs){
      if(this.props.editRecord.configs.management_companies.length===10){
        company_sign=''
      }
      if(this.props.editRecord.configs.management_companies.length===6){
        company_sign='e'
      }
      if(this.props.editRecord.configs.management_companies.length===4){
        company_sign='w'
      }
    }
    console.log('this.state.all_permission',this.state.all_permission)
    return (
      <div>
        <Row gutter={16}>
          <Col className="gutter-row" span={this.state.all_permission===1?24:12}>
            <h2>基本信息</h2>
            <Form onSubmit={this.handleSubmit}>
              <FormItem
                {...formItemLayoutWithLabel}
                label={(
                  <span>
                账号名称
            </span>
                )}
              >
                {getFieldDecorator('username', {
                  initialValue: this.props.editRecord ? this.props.editRecord.username : '',
                  rules: [{ required: true, message: '请输入名称' }],
                })(
                  <Input />
                )}
              </FormItem>
              {
                !this.props.editRecord &&
                <FormItem
                  {...formItemLayoutWithLabel}
                  label={
                    <span>新密码  <Tooltip title="密码必须包含数字、小写字母、大写字母各1个，长度为8-16，非空白字符"><Icon type="exclamation-circle" /></Tooltip></span>
                  }
                >
                  {getFieldDecorator('password', {
                    initialValue: this.props.editRecord ? this.props.editRecord.password : '',
                    rules: [{ required: true, message: '请输入初始密码' }],
                  })(
                    <Input.Password  onChange={this.changePassword}/>
                  )}
                </FormItem>
              }
              {
                !this.props.editRecord &&<FormItem
                  label="密码强度(必须为强)"
                  {...formItemLayoutWithLabel}
                >
                  <div className={styles.strength_box}>
                    <div className={styles.one} style={{background:this.state.level>=1?'#F5222D':'#cccccc'}}>
                      <span></span>
                      <p>弱</p>
                    </div>
                    <div className={styles.two} style={{background:this.state.level>=2?'#FAAD14':'#cccccc'}}>
                      <span></span>
                      <p>中</p>
                    </div>
                    <div className={styles.three} style={{background:this.state.level>=3?'#52C41A':'#cccccc'}}>
                      <span></span>
                      <p>强</p>
                    </div>
                  </div>
                </FormItem>
              }
              <Form.Item label={<span><span style={{color:'red'}}>* </span>权限信息</span>}
                         {...formItemLayoutWithLabel}
              >
                {getFieldDecorator('all_permission', {
                  initialValue:this.state.all_permission,
                  //rules: [{ required: true, message: '请选择' }],
                })(
                  <Select  placeholder="请选择" onChange={(e)=>{
                    console.log('e',e)
                    this.setState({
                      all_permission:e
                    })
                  }}>
                    <Option value={1}>全部权限</Option>
                    <Option value={-1}>自定义权限</Option>
                  </Select>,
                )}
              </Form.Item>

            </Form>
          </Col>
          {
            this.state.all_permission!==1&&
            <Col className="gutter-row" span={12}>
              <h2>权限信息</h2>
              <div style={{height:'550px',overflowY:'scroll'}}>
                {this.renderXheckGroup(this.state.group)}
              </div>

            </Col>
          }

        </Row>

      </div>
    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default connect()(AddPoliciesFormWrap);


